/*****************************************************************
 *Yuga Technology
 *@author Oplink OMS
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webems.modules.cfg.web;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.oplink.webems.common.persistence.Page;
import com.oplink.webems.common.snmp.CardParser;
import com.oplink.webems.common.snmp.base.SnmpException;
import com.oplink.webems.common.snmp.entity.Card;
import com.oplink.webems.common.snmp.service.SnmpService;
import com.oplink.webems.modules.cfg.entity.CfgCard;
import com.oplink.webems.modules.cfg.entity.CfgCardValue;
import com.oplink.webems.modules.cfg.entity.CfgSlot;
import com.oplink.webems.modules.cfg.services.CfgCardService;
import com.oplink.webems.modules.cfg.services.CfgCardValueService;
import com.oplink.webems.modules.cfg.services.CfgNeService;
import com.oplink.webems.modules.cfg.services.CfgSlotService;
import com.oplink.webems.modules.sys.dto.MsgDTO;
import com.oplink.webems.modules.sys.dto.RespDTO;
import com.oplink.webems.modules.sys.entity.Dict;
import com.oplink.webems.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webems.modules.sys.utils.DictUtils;
import com.oplink.webems.modules.sys.web.BaseController;

/**
 * 配置管理的Controller, 使用Restful风格的Urls:
 * List page : GET /queue/
 * Create pushlet : GET /queue/pushlet
 * Create page : GET /queue/create
 * Create action : POST /queue/create
 * Update page : GET /queue/update/{id}
 * Update action : POST /queue/update
 * Delete action : GET /queue/delete/{id}
 * 告警Controller
 * 
 * @author Oplink OMS
 * @version 2014-08-11
 */
@Controller
@RequestMapping(value = "cfg/card")
public class CfgCardController extends BaseController {

	@Autowired
	private CfgCardService cardService;

	@Autowired
	private CfgNeService neService;

	@Autowired
	private CfgSlotService slotService;

	@Autowired
	private CfgCardValueService valueService;

	@Autowired
	private SnmpService snmpService;

	@RequestMapping(value = "")
	public String cardCfg(CfgCard card, HttpServletRequest request, HttpServletResponse response, Model model) {
		/*
		 * Page<CfgValue> pages = cfgService.findFormPaging(new Page<CfgValue>(request, response),
		 * UserUtils.getCurrentUserId(), "mgr_card", request.getParameter("mgr_ne_name"));
		 * model.addAttribute("pages", pages);
		 */
		Page<CfgCard> page = cardService.find(new Page<CfgCard>(request, response), card);
		model.addAttribute("pages", page);
		model.addAttribute("entity", card);
		return "modules/cfg/cardIndex";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public CfgCard updateForm(@PathVariable("id") Long id) {
		CfgCard card = cardService.getCfgCard(id);
		return card;
	}

	@RequestMapping(value = "remote/{cid}", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> remote(HttpServletRequest request, @PathVariable("cid") Long cid) {
		Map<String, String> outMap = new HashMap<String, String>();
		String params = request.getParameter("jsonData");
		if (params != null) {
			String[] listParam = params.split(",");
			if (listParam.length > 0) {
				try {
					CfgCard card = cardService.getCfgCard(cid);
					Card scp = CardParser.toSnmpCard(card);
					return snmpService.getMap(scp, Arrays.asList(listParam));
				} catch (SnmpException e) {
					e.printStackTrace();

				}
			}
		}
		return outMap;
	}

	/**
	 * 获得所有板卡属性
	 * 
	 * @return
	 */
	@RequestMapping(value = "getAllCardConfig", method = RequestMethod.GET)
	@ResponseBody
	public List<CfgSlot> getAllCardConfig() {
		return cardService.getAll();
	}

	/**
	 * 
	 * @param nid 网元id
	 * @param ctype 板卡类型
	 * @return
	 */
	@RequestMapping(value = "addCard/{nid}/{sid}/{ctype}", method = RequestMethod.GET)
	@ResponseBody
	public RespDTO addCard(@PathVariable("nid") Long nid, @PathVariable("sid") Long sid,
			@PathVariable("ctype") String ctype) {
		return cardService.addCard(nid, sid, ctype, neService, snmpService);
	}

	@RequestMapping(value = "delCard/{nid}/{sid}", method = RequestMethod.GET)
	@ResponseBody
	public RespDTO delCard(@PathVariable("nid") Long nid, @PathVariable("sid") Long sid) {
		return cardService.delCard(nid, sid, neService, snmpService);
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public RespDTO update(@Valid @ModelAttribute("entity") CfgCard entity, RedirectAttributes redirectAttributes) {
		RespDTO res = new RespDTO(RespDTO.ERROR, "");
		try {
			cardService.saveCfgCard(entity);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			res.setResult(RespDTO.SUCCESS);
			res.setMessage(MsgDTO.OK_SAVE_SUCCESS);
			return res;
		} catch (Exception e) {
			return res;
		}
	}

	/**
	 * 保存板卡记录
	 * 
	 * @param card
	 * @param redirectAttributes
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public RespDTO create(@Valid CfgCard entity, RedirectAttributes redirectAttributes, Model model) {
		RespDTO res = new RespDTO(RespDTO.ERROR, "");
		try {
			cardService.saveCfgCard(entity);
			redirectAttributes.addFlashAttribute("message", "创建任务成功");
			res.setResult(RespDTO.SUCCESS);
			res.setMessage(MsgDTO.OK_SAVE_SUCCESS);
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			return res;
		}
	}

	/**
	 * 更新板卡配置参数
	 * 
	 * @param cid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "saveData/{cid}", method = RequestMethod.POST)
	@ResponseBody
	public RespDTO saveData(@PathVariable("cid") String cid, HttpServletRequest request) {
		RespDTO rest = new RespDTO(RespDTO.ERROR, MsgDTO.ERR_SAVE_FAILURE);
		try {
			if ((cid != null) && !cid.equals("") && !cid.equals("0")) {
				String jsonData = request.getParameter("jsonData");
				Map<String, String> hshMap = new HashMap<String, String>();
				JSONObject valMap = (JSONObject) JSONObject.parse(jsonData);
				Long cardid = Long.parseLong(cid);
				CfgCard card = cardService.getCfgCard(cardid);
				List<CfgCardValue> listValue = card.getCardVallist();
				Iterator<String> keyIter = valMap.keySet().iterator();
				while (keyIter.hasNext()) {
					String key = keyIter.next();
					String value = valMap.getString(key);
					CfgCardValue val = getCardVal(key, listValue);
					if (val != null) {
						// 更新
						val.setValue(value);
						valueService.saveValue(val);
					} else {
						// 创建
						createNewValue(card, key, value);
					}
					// 给新的hashMap赋值
					hshMap.put(key, value);
				}

				try {
					// 保存到设备中
					Card snmpCard = CardParser.toSnmpCard(card);
					Map<String, Boolean> result = snmpService.setMap(snmpCard, hshMap);
				} catch (Exception e) {
					e.printStackTrace();
					rest.setResult(RespDTO.ERROR);
					rest.setMessage(MsgDTO.ERR_SAVE_DEVICE_CARD);
				}

				// 更新值
				/*
				 * if (listValue.size() > 0) {
				 * for (CfgCardValue value : listValue) {
				 * String fieldValue = (String) valMap.get(value.getField());
				 * if (null != fieldValue) {
				 * value.setValue(fieldValue);
				 * valueService.saveValue(value);
				 * } else {
				 * // 有新字段增加的时候
				 * createNewValue(valMap, cid);
				 * }
				 * }
				 * } else {
				 * // 初始化的时候
				 * createNewValue(valMap, cid);
				 * }
				 */
			}
			return rest;
		} catch (Exception e) {
			e.printStackTrace();
			return rest;
		}
	}

	private CfgCardValue getCardVal(String field, List<CfgCardValue> listValue) {
		for (CfgCardValue val : listValue) {
			if (val.getField().equals(field)) {
				return val;
			}
		}
		return null;
	}

	/**
	 * 创建新的板卡值
	 * 
	 * @param valMap
	 * @param card
	 * @param cid
	 * @return
	 */
	private void createNewValue(CfgCard card, String key, String value) {
		CfgCardValue cardValue = new CfgCardValue();
		cardValue.setCard(card);
		cardValue.setField(key);
		cardValue.setValue(value);
		valueService.saveValue(cardValue);
	}

	/**
	 * 判断数组是否存在指定字段
	 * 
	 * @param field
	 * @param listValue
	 * @return
	 */
	private boolean existField(String field, List<CfgCardValue> listValue) {
		for (CfgCardValue v : listValue) {
			if (v.getField().equals(field)) {
				return true;
			}
		}
		return false;
	}

	@RequestMapping(value = "updateData/{cid}", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> updateData(@PathVariable("cid") String cid) {
		Map<String, String> outMap = new HashMap<String, String>();
		try {
			if ((cid != null) && !cid.equals("")) {
				Long cardid = Long.parseLong(cid);
				CfgCard card = cardService.getCfgCard(cardid);
				List<CfgCardValue> listValue = card.getCardVallist();
				for (CfgCardValue cv : listValue) {
					outMap.put(cv.getField(), cv.getValue());
				}
				return outMap;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 通过slot id查找指定的slot
	 * 
	 * @param listSlots 查找集合
	 * @param sid 主键id
	 * @return
	 */
	private CfgSlot getSlot(List<CfgSlot> listSlots, Long sid) {
		for (CfgSlot slot : listSlots) {
			if (slot.getSlotid().equals(sid)) {
				return slot;
			}
		}
		return null;
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					// 从程序上解除级联关系.
					CfgCard card = cardService.getCfgCard(Long.valueOf(idItem));
					List<CfgSlot> listSlots = card.getSlotlist();
					for (CfgSlot slot : listSlots) {
						slot.setCard(null);
					}
					card.setSlotlist(null);
					cardService.deleteCfgCard(card.getCardid());
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "listCardType")
	@ResponseBody
	public List<Dict> listCardType() {
		return DictUtils.getDictList("mgr_card_type");
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
